package com.sh.data.engine.domain.annotation;

import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.common.util.ServletUtils;
import com.sh.data.engine.domain.shims.db.BaseDbManager;
import com.sh.data.engine.domain.workspace.index.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class StorageCheckAspect {

    @Autowired
    private ProjectService projectService;

    @Pointcut("@annotation(com.sh.data.engine.domain.annotation.StorageCheckAnnotation)")
    public void annotationPointCut() {
    }

    @Before("annotationPointCut()")
    public void doCheck() throws Throwable {
        var projectId = ServletUtils.getProjectId();
        BaseDbManager dbManager = projectService.getDbManager(projectId);
        try {
            dbManager.testConnection();
        } catch (Exception e) {
            log.info("aop storage check error : {}", e.getMessage());
            throw new BusinessException("检查当前工作空间的底层存储状态");
        } finally {
            if (null != dbManager) {
                dbManager.close();
            }
        }
    }
}
